package App.Controleur;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;

import App.Modele.Partie;

/**
 * Classe d'interface avec le système de fichiers dédié aux sauvegardes.
 * @author BlackPearl
 *
 */
public abstract class JSparrow_FileSystem {
	public final static String jsHome = System.getProperty( "user.home" ) + "/.JSparrow";
	public final static String jsSaves = jsHome + "/Saves";
	public static File jsDir;
	public static File jsSavesDir;
	public static void initFS()
	{
		jsDir = new File(jsHome);
		jsSavesDir = new File(jsSaves);
		
		if(!jsDir.exists())
		{
			jsDir.mkdir();
		}
		if(!jsSavesDir.exists())
		{
			jsSavesDir.mkdir();
		}
	}
	
	@SuppressWarnings("resource")
	public static ArrayList<Partie> getSavedParties()
	{
		initFS();
		
		ArrayList<Partie> result = new ArrayList<Partie>();
		
		File[] fileList = jsSavesDir.listFiles();
		for (File file : fileList) {
			try {
				FileInputStream IS = new FileInputStream(file);
				ObjectInputStream ois = new ObjectInputStream(IS);
				result.add((Partie) ois.readObject());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	public static void savePartie(Partie p)
	{
		initFS();
		p.setDateEnregistrement(new Date());
		ObjectOutputStream oos;
		try {
			FileOutputStream f = new FileOutputStream(jsSaves + "/" + p.getNom() + "_save.jspw");
			oos = new ObjectOutputStream(f);
			oos.writeObject(p);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}
	
	
}
